package com.typhosoft.photohz2o.server;

import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.FrameworkMessage;
import com.esotericsoftware.kryonet.Listener;
import com.typhosoft.jcommon.bean.CLoginMessage;
import com.typhosoft.jcommon.bean.CUser;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by Mario on 24/03/2014.
 */
public class CLogInConsumer extends Listener {

    private final static ArrayBlockingQueue<List> fConnectedClient = new ArrayBlockingQueue<>(100);

    public CLogInConsumer() {

    }

    @Override
    public void connected(Connection connection) {
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Connected To: ", connection);
    }

    @Override
    public void disconnected(Connection connection) {
        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Disconnected From: ", connection);
    }

    @Override
    public void received(Connection connection, Object o) {

        Logger.getLogger(this.getClass().getName()).log(Level.INFO, "Received: object[" + o + "]", connection);
        if (o instanceof CLoginMessage) {
            CLoginMessage logIn = (CLoginMessage) o;
            fConnectedClient.offer(Arrays.asList(logIn, connection, new Date()));

        } else if (o instanceof FrameworkMessage.KeepAlive) {

        }
    }

    public Connection getNextUser(CUser user) throws InterruptedException {
        Connection connection;
        List client;
        client = fConnectedClient.take();
        if (((CLoginMessage) client.get(0)).getUser().equals(user)) {
            connection = getNextUser(user);
            fConnectedClient.offer(client);
        } else {
            connection = (Connection) client.get(1);
        }

        return connection;
    }
}
